package com.ff.sca.suser.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ff.sca.common.entity.ztree.MenuNode;
import com.ff.sca.common.entity.ztree.ZtreeNode;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.suser.dao.ScaPermissionDao;
import com.ff.sca.suser.dao.ScaSysUserDao;
import com.ff.sca.suser.entity.ScaPermission;
import com.ff.sca.suser.entity.ScaSysUser;
import com.ff.sca.suser.service.IScaSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * sca后台管理员用户 服务实现类
 * </p>
 *
 * @author gw
 * @since 2018-09-20
 */
@Service
public class ScaSysUserServiceImpl extends ServiceImpl<ScaSysUserDao, ScaSysUser> implements IScaSysUserService {

    @Autowired
    private ScaSysUserDao sysUserDao;
    @Autowired
    private ScaPermissionDao permissonDao;

    @Override
    public List<MenuNode> getUserMenuList(Integer userId, Integer pid) {
        // TODO Auto-generated method stub
        if (CharUtil.isEmpty(pid)) {
            pid = 0;
        }
        List<ScaPermission> permisonList = sysUserDao.getUserMenuList(userId, pid);
        return createZtreeNode(permisonList);
    }

    /**
     * 组装ztreeNode
     *
     * @param permisonList
     * @return
     */
    private List<MenuNode> createZtreeNode(List<ScaPermission> permisonList) {
        List<MenuNode> nodes = new ArrayList<>();
        if (permisonList.size() > 0) {
            for (int i = 0; i < permisonList.size(); i++) {
                ScaPermission per = permisonList.get(i);
                MenuNode node = new MenuNode();
                node.setId(per.getId());
                node.setName(per.getName());
                node.setIcon(per.getIcon());
                node.setUrl(per.getUrl());
                List<ScaPermission> PermissonChildrenList = permissonDao
                        .selectList(new EntityWrapper<ScaPermission>().eq("pid", per.getId()).orderBy("sort", true));
                if (PermissonChildrenList.size() > 0) {
                    node.setChildren(createZtreeNode(PermissonChildrenList));
                }
                nodes.add(node);
            }
        }
        return nodes;
    }
}
